/*
 * SyncResource.java
 *
 * Created on April 12, 2007, 1:39 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.atomojo.app.admin;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import org.atomojo.app.App;
import org.atomojo.app.db.DB;
import org.atomojo.app.db.DBConnection;
import org.restlet.data.CharacterSet;
import org.restlet.data.MediaType;
import org.restlet.representation.OutputRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.ServerResource;

/**
 *
 * @author alex
 */
public class TableDumpResource extends ServerResource implements AdminXML
{
   public TableDumpResource() {
      setNegotiated(false);
   }

   public Representation get()
   {
      final DB db = (DB)getRequest().getAttributes().get(App.DB_ATTR);
      final String name = getRequest().getAttributes().get("name").toString();

      Representation rep = new OutputRepresentation(MediaType.APPLICATION_XML) {
         public void write(OutputStream os)
            throws IOException
         {
            Writer out = new OutputStreamWriter(os,"UTF-8");
            out.write("<table name='"+name+"'>\n");
            try {
               DBConnection dbConnection = db.getConnection();
               try {
                  Statement s = dbConnection.getConnection().createStatement();
                  ResultSet r = s.executeQuery("select * from "+name);
                  ResultSetMetaData meta = r.getMetaData();
                  int columnCount = meta.getColumnCount();
                  out.write("<head>");
                  for (int i=1; i<=columnCount; i++) {
                     out.write("<name>");
                     out.write(meta.getColumnName(i));
                     out.write("</name>");
                  }
                  out.write("</head>\n");
                  while (r.next()) {
                     out.write("<row>");
                     for (int i=1; i<=columnCount; i++) {
                        String data = r.getString(i);
                        if (data!=null) {
                           out.write("<col>");
                           out.write(data);
                           out.write("</col>");
                        } else {
                           out.write("<col/>");
                        }
                     }
                     out.write("</row>\n");
                  }
               } finally {
                  db.release(dbConnection);
               }
            } catch (SQLException ex) {
               throw new IOException(ex.getMessage());
            }
            out.write("</table>");
            out.flush();
         }
      };
      rep.setCharacterSet(CharacterSet.UTF_8);
      return rep;
   }
   
  
}
